<template>
  <div>
    <el-dialog v-model="dialogFormVisible" :title="type == 'add' ? '新增商品' : '修改商品'">
      <el-form ref="ruleFormRef" :rules="rules" :model="form">
        <el-form-item label="品牌名称" label-width="140px" prop="tmName">
          <el-input v-model="form.tmName" autocomplete="off" />
        </el-form-item>

        <el-form-item label="品牌Logo" label-width="140px" prop="logoUrl">
          <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="form.logoUrl" :src="form.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="conifrm(ruleFormRef, $parent)"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<!-- 添加或者编辑的对话框表单 -->
<script setup lang="ts">
import { reactive, ref } from 'vue'
import type { FormInstance, UploadProps, FormRules } from 'element-plus'
import { postAddTrademark, putTrademark } from '@/utils/api/product/trademark'

const dialogFormVisible = ref(false)
const ruleFormRef = ref<FormInstance>()

const props = defineProps({
  type: String,
  trade: Object
})

interface RuleForm {
  tmName: string
  logoUrl: string
}

const form = reactive({
  id: 0,
  tmName: '',
  logoUrl: ''
})

// 表单验证
const rules = reactive<FormRules<RuleForm>>({
  tmName: [
    { required: true, message: '请输入名字', trigger: 'blur' },
    { min: 2, message: '名字至少为两位', trigger: 'blur' }
  ],
  logoUrl: {
    required: true,
    message: '请插入图片'
  }
})

// 上传成功的回调
const handleAvatarSuccess: UploadProps['onSuccess'] = response => {
  form.logoUrl = response.data
}

// 图片上传之前的操作
const beforeAvatarUpload: UploadProps['beforeUpload'] = rawFile => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('图片必须是jpeg或者是png格式')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片不能超过2mb')
    return false
  }
  return true
}

// 点击确认按钮
const conifrm = async (formEl: FormInstance | undefined, $parent: any) => {
  if (!formEl) return

  await formEl.validate(valid => {
    if (valid) {
      if (props.type == 'add') {
        addTrademark($parent)
      } else {
        editTrad($parent)
      }
    } else {
      ElMessage.error('请把信息填写完整')
      return
    }
  })
}

// 新增图片
const addTrademark = async ($parent: any) => {
  const res = await postAddTrademark({ tmName: form.tmName, logoUrl: form.logoUrl })
  if (res.data.code == 200) {
    ElMessage.success('添加成功')
    dialogFormVisible.value = false
    $parent.getTableData()
  }
}

// 清除表单验证和表单数据
const cleanFormVaild = () => {
  ruleFormRef.value?.clearValidate()
  ruleFormRef.value?.resetFields()
}

// 取消按钮
const cancel = () => {
  dialogFormVisible.value = false
}

// 修改商品
const editTrad = async ($parent: any) => {
  const res = await putTrademark(form)
  if (res.data.code == 200) {
    ElMessage.success('修改成功')
    dialogFormVisible.value = false

    $parent.getTableData($parent.tradeTable.length == 1 ? $parent.currentPage - 1 : $parent.currentPage)
  }
}

// 暴露让父组件拿到该值
defineExpose({ dialogFormVisible, cleanFormVaild, form })
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
